<template>
  <div>
    <el-form label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model="spuForm.spuName"></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select v-model="spuForm.tmId" placeholder="请选择">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in trademarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          v-model="spuForm.description"
          rows="4"
          type="textarea"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          v-model="saleAttrIdName"
          :placeholder="
            unUsedSaleAttrList.length > 0
              ? `还有${unUsedSaleAttrList.length}未选择`
              : '没有啦！！！'
          "
        >
          <el-option
            v-for="(unUsedSaleAttr) in unUsedSaleAttrList"
            :key="unUsedSaleAttr.id"
            :label="unUsedSaleAttr.name"
            :value="`${unUsedSaleAttr.id}:${unUsedSaleAttr.name}`"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!saleAttrIdName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table border style="width: 100%" :data="spuForm.spuSaleAttrList">
          <el-table-column
            type="index"
            align="center"
            prop="prop"
            label="序号"
            width="80"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="150">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, }">
              <!--  @close="handleClose(tag)" 点击x的时候再用 -->
              <el-tag
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>

              <!-- v-model="row.inputValue" 就算这个属性不存在，用户只要输入了东西，这个属性就会自动创建并且响应式 -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.saleAttrValueName"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <!--   -->
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ 添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{ $index }">
              <HintButton
                type="danger"
                icon="el-icon-delete"
                size="mini"
                title="删除销售属性"
                @click="spuForm.spuSaleAttrList.splice($index, 1)"
              ></HintButton>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  props: ["visible"],
  data() {
    return {
      category3Id: "",
      spuForm: {
        category3Id: 0,
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [],
        spuSaleAttrList: [], //spu自己的销售属性列表
      },
      spuImageList: [], // 图片列表
      trademarkList: [], //品牌列表
      baseSaleAttrList: [], // 销售属性列表
      dialogVisible: false,
      saleAttrIdName: "",
      dialogImageUrl: "",
    };
  },
  methods: {
    handleSuccess(res, file, fileList) {
      // console.log(res, file, fileList)
      this.spuImageList = fileList;
    },

    // 删除图片的时候，需要收集图片列表
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.spuImageList = fileList;
    },
    // 预览大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 函数初始化请求数据
    async getInitUpdateSpuFormData(row, category3Id) {
      this.category3Id = category3Id;
      // 根据id获取SPU详情信息
      const result1 = await this.$API.spu.get(row.id);
      if (result1.code === 200 || result1.code === 20000) {
        this.spuForm = result1.data;
      }

      // 获取spuid对应的图片列表
      const result2 = await this.$API.sku.getSpuImageList(row.id);
      if (result2.code === 200 || result2.code === 20000) {
        let spuImageList = result2.data;
        spuImageList.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = spuImageList;
      }
      // 获取所有的品牌列表
      const result3 = await this.$API.trademark.getList();
      if (result3.code === 20000 || result3.code === 200) {
        this.trademarkList = result3.data;
      }

      // 获取所有的销量属性列表
      const result4 = await this.$API.spu.getSaleAttrList();
      if (result4.code === 20000 || result4.code === 200) {
        this.baseSaleAttrList = result4.data;
      }
    },

    async getInitAddSpuFormData(category3Id){
      this.category3Id = category3Id
      // 获取所有品牌列表
      const result1 = await this.$API.trademark.getList()
      if(result1.code === 20000 || result1.code ===200){
        this.trademarkList = result1.data
      }
      // 获取所有销售属性列表
      const result2 = await this.$API.spu.getSaleAttrList()
      if(result2.code === 20000 || result2.code === 200){
        this.baseSaleAttrList = result2.data
      }
    },

    //input失去焦点，把刚才收集的用户输入的数据，获取到，变为一个对象，添加到row.spuSaleAttrValueList当中
    handleInputConfirm(row) {
      let { saleAttrValueName, baseSaleAttrId } = row;
      // console.log(saleAttrValueName)
      let obj = { saleAttrValueName, baseSaleAttrId };

      //判断数据如果为空，不发请求
      if (saleAttrValueName.trim() === "") {
        row.saleAttrValueName = "";
        row.inputVisible = false;
        return;
      }

      let isRepeat = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName === saleAttrValueName
      );
      if (isRepeat) {
        this.$message.success("属性值不能重复");
        row.saleAttrValueName = "";
        return;
      }

      row.spuSaleAttrValueList.push(obj);
      //清空当前input数据
      row.saleAttrValueName = "";
      //input切换为button
      row.inputVisible = false;
    },

    // 添加销售属性
    addSaleAttr() {
      let [baseSaleAttrId, saleAttrName] = this.saleAttrIdName.split(":");

      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };

      this.spuForm.spuSaleAttrList.push(obj);

      this.saleAttrIdName = "";
    },

    //保存操作
    async save() {
      //获取请求参数
      let { spuForm, spuImageList, category3Id } = this;
      spuForm.category3Id = category3Id;
      spuForm.spuImageList = spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data,
        };
      });

      spuForm.spuSaleAttrList.forEach((item) => {
        delete item.inputVisible;
        delete item.saleAttrValueName;
      });
      //发请求
      try {
        //成功
        const result = await this.$API.spu.addUpdate(spuForm);
        if (result.code === 200 || result.code === 20000) {
          this.$message.success("保存spu成功");
          this.$emit("update:visible", false);

          // 再次出发另外一个自定义事件，告诉爹回来了
          this.$emit("backSuccess");
          //清空data当中所有的数据
          this.resetData();
        } else {
          this.$message.error("保存spu失败");
        }
      } catch (error) {
        //失败
        this.$message.error("保存spu请求失败");
      }
    },
    //清空data的数据
    resetData() {
      this.dialogImageUrl = ""; //预览大图当中dialog内部的img图片路径
      this.dialogVisible = false; //点击方大弹出dialog
      this.saleAttrIdName = "";
      this.spuForm = {
        category3Id: 0,
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [],
        spuSaleAttrList: [], //spu自己的销售属性列表
      };
      this.category3Id = "";
      this.spuImageList = []; //收集图片列表先收集到这里，然后最后再整理到spuForm内部
      this.trademarkList = [];
      this.baseSaleAttrList = []; //所有的销售属性列表
    },
    //取消操作
    cancel() {
      //返回到父组件
      this.$emit("update:visible", false);
      //清空数据
      this.resetData();
      //清空父组件的标志位
      this.$emit("cancelBack");
    },
  },

  computed: {
    unUsedSaleAttrList() {
      return this.baseSaleAttrList.filter((item) => {
        this.spuForm.spuSaleAttrList.every((item1) => {
          item.name !== item1.name;
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
</style>
